package com.xin.springcloudconsumer.controller;

import com.xin.springcloudconsumer.config.ProjectUrlConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 调用微信测试号授权服务
 */
@Controller
@RequestMapping("wx")
public class WxAuthController {
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/auth")
    public ModelAndView auth(){
        String returnUrl=projectUrlConfig.localUrl+"/wx/success";
        String url=projectUrlConfig.wxAuthUrl+"/wx/authorize".concat("?returnUrl=").concat(returnUrl);
        return new ModelAndView("redirect:".concat(url));
    }
    @GetMapping("/success")
    public ModelAndView success(@RequestParam(value = "result",defaultValue = "")String result,
                                Map<String,Object> map,
                                HttpServletRequest request){
         if (StringUtils.isEmpty(result)){
               //TODO 跳转
                String returnUrl="/ftl/auth";
                map.put("returnUrl",returnUrl);
                map.put("message","授权失败!");
                return new ModelAndView("common/msg_error",map);
         }
        String[] split = result.split(",");
        String openId=split[0];
        String headImage=split[1];
        request.getSession().setAttribute("token",openId);
        request.getSession().setAttribute("headImage",headImage);
        //TODO 跳转页面
        return new ModelAndView("redirect:/ftl/findAll");
    }

}
